package nl.xvr.server.control;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Properties;
import java.util.concurrent.Semaphore;

public class ControlServer extends Thread
{
    private int port;
    private Semaphore semaphore;
    private Properties properties;
    private ServerSocket sockListen;

    public ControlServer(Properties properties, Semaphore semaphore) {
        this.port = Integer.parseInt(properties.getProperty("control_port"));
        this.properties = properties;
        this.semaphore = semaphore;
    }

    public void run() {
        try {
            System.out.println("Start control server...");
            sockListen = new ServerSocket(port);

            while (true)
            {
                try {
                    new RequestHandler(properties, sockListen.accept(), semaphore).start();
                }
                catch (IOException e) {
//                    System.err.println("Could not accept socket listener for control server: "
//                            + e);
                    return;
                } 
            }
        } catch (IOException e) {
            System.err.println("Could not start control server: " + e);
            System.exit(-1);
        }
    }

    public void closeServer() {
        try {
            sockListen.close();
        }
        catch (IOException e) {
            System.err.println("Could not stop server: " + e);
        }
    }
}
